//
//  WSCollectionController.swift
//  demo
//
//  Created by 武莎莎 on 15/9/12.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let WSMaxPictureAmount = 9
class WSSelectPicture: UICollectionViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, WSSelectPictureCellDelegate{
    // 数据源
    private lazy var pictures = [UIImage]()
    // 记录当前图片的索引，实现当用户删除一个图片在添加的时候添加到原来的位置
    private var currentIndex = 0
    
    // 注册layout
    init(){
        let layout = UICollectionViewFlowLayout()
        super.init(collectionViewLayout: layout)
        // 设置左右的间距
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
        layout.itemSize = CGSizeMake(80, 80)

    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView?.backgroundColor = UIColor(white: 0.97, alpha: 1.0)
        
        // 注册cell
        self.collectionView!.registerClass(WSSelectPictureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return pictures.count + (pictures.count == WSMaxPictureAmount ? 0 : 1)
    }
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! WSSelectPictureCell
        
        cell.pictureDelegate = self
        
        cell.image = indexPath.item < pictures.count ? pictures[indexPath.item] : nil
        
        return cell
    }
    
    // MARK:WSSelectPictureCellDelegate代理方法的实现
    private func selectPictureCelldidClickedRemoveBtn(cell: WSSelectPictureCell) {
       
        // 如果indexpath有值，才会执行后面{}的内容
        // where 后面的语句防止点击加号上面的删除按钮造成的数组越界
        if let indexPath = collectionView?.indexPathForCell(cell) where indexPath.item < pictures.count {
            pictures.removeAtIndex(indexPath.item)
            collectionView?.reloadData()
        }
    }
    
    //MARK:colletionView的代理方法
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // 判断资源是否可用
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            print("没有可用的图片")
            return
        }
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        
        currentIndex = indexPath.item
        
        presentViewController(imagePicker, animated: true, completion: nil)
    }
}

// MARK: UIImagePickerControllerDelegate, UINavigationControllerDelegate代理
extension WSSelectPicture {
    // 一旦实现了UIImagePickerControllerDelegate的代理方法，就需要手动关闭UIImagePickerController了
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let scaleImage = image.scaleImageToWidth(300)
        if currentIndex < pictures.count {
            // 替换掉当前位置的图片
            pictures[currentIndex] = scaleImage
        }else {
            pictures.append(scaleImage)
        }
        collectionView?.reloadData()

        dismissViewControllerAnimated(true, completion: nil)
    }
}
// 1、定义照片cell的协议
private protocol WSSelectPictureCellDelegate: NSObjectProtocol {
    func selectPictureCelldidClickedRemoveBtn(cell: WSSelectPictureCell)
}
// MARK:自定义collectionCell
private class WSSelectPictureCell:UICollectionViewCell {
    
    //2、定义代理属性
    weak var pictureDelegate:WSSelectPictureCellDelegate?
    
    // cell上面显示的图片
    private var image:UIImage? {
        didSet{
            if image == nil {
                pictureBtn.setImage(UIImage(named:"compose_pic_add"), forState: UIControlState.Normal)
            } else{
                pictureBtn.setImage(image, forState: .Normal)
            }
            
            removeBtn.hidden = (image == nil)
        }
    }
    // 3、在适当的时候调用代理的代理方法 OC中需要判断代理方法是否实现，如果没有实现就调用的话会崩。Swift中delegate属性使可选的，如果没有代理的话就不会继续往下执行，不会崩
    @objc private func removePictureBtnClicked() {
        pictureDelegate?.selectPictureCelldidClickedRemoveBtn(self)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        // 跟tableView的cell一样，添加控件要添加到contentView中
        contentView.addSubview(pictureBtn)
        contentView.addSubview(removeBtn)
        // 添加约束
        pictureBtn.frame = bounds
        pictureBtn.userInteractionEnabled = false
        
        let viewDict = ["btn":removeBtn]
        removeBtn.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[btn]-0-|", options: [], metrics: nil, views: viewDict))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[btn]", options: [], metrics: nil, views: viewDict))
        
        removeBtn.addTarget(self, action: "removePictureBtnClicked", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 设置按钮中imageView的contentMode，否则有些图片会变形，默认为scaleToFill
        pictureBtn.imageView!.contentMode = UIViewContentMode.ScaleAspectFill
    }
    private var pictureBtn = UIButton(imageName: "compose_pic_add")
    private var removeBtn = UIButton(imageName: "compose_photo_close")
}